package filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(filterName = "AdminLoginFilter")
public class AdminLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpSession session = ((HttpServletRequest) request).getSession();
        // 获取session中的Username信息
        String username = (String) session.getAttribute("admin_username");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 正则匹配login相关页面（login.jsp和login_deal.jsp
        boolean isLoginPath = httpServletRequest.getServletPath().matches(".*login.*");
        // 正则匹配UserServlet
        boolean isUserServlet = httpServletRequest.getServletPath().matches(".*AdminServlet.*");
        // 判断是否为登录状态以及是否为白名单页面
        if (username != null || isLoginPath || isUserServlet) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).sendRedirect("/admin/login.jsp");
        }
    }
}
